02 / 02

Explain how will you implement authentication in a react/nextjs app.

We can either use JWT or opaque tokens. We prefer JWT for horizontally scaled systems or distributed systems or if we want to avoid database lookups, and chose opaque tokens if instant logout, instant revocation, session tracking, device management

Database schema
  1. 1

    Users: Table or collection for storing user information

  2. 2

    Sessions/Tokens: Table or collection to store session /token infromation

  3. 3

    Store a SHA-256 hash of the refresh token, never the token itself. The actual token is only given to the client in the cookie.

Sign‑up & Login (Server Actions): Sign‑up follows the same pattern, but creates the user first.
Automatic token refresh in middleware: Because the access token expires quickly, we refresh it silently. This is best done in middleware, which runs on every request.
Logout:
Exposing user data to Server Components
Exposing user data to Client Components
Route protection with middleware and in pages
  1. 1

    We already saw middleware protecting /account and /checkout. But for fine‑grained role‑based access, you can also check in Server Components or in the layout, because middleware doesn’t have access to full request body and you may need DB data.

  2. 2

    Middleware handles broad redirection (unauthenticated → login).

  3. 3

    Server Components check roles and show 403 or redirect if needed.

  4. 4

    Client Components can conditionally render UI using useAuth().

Security hardening checklist
  1. 1

    Passwords: hash with bcrypt (cost ≥ 12). Never store plaintext.

  2. 2

    Cookies: httpOnly, Secure, SameSite=Lax. Path=/. For extra protection against CSRF, you can add a custom request header validation.

  3. 3

    Refresh token rotation: each time a refresh token is used, issue a new one and invalidate the old. This limits the window if a token is stolen.

  4. 4

    Rate limiting: protect login/server actions with a rate limiter (e.g., using Upstash Ratelimit or a custom in‑memory store). Prevents brute‑force.

  5. 5

    Token expiry: keep access token short (5‑15 min). Refresh token can be longer (7‑30 days), but must be revocable.

  6. 6

    CORS & CSP: properly set Content Security Policy headers to mitigate XSS. Since we use httpOnly cookies, XSS cannot directly steal tokens, but still guard your app.

  7. 7

    Secure session termination: on password change or suspicious activity, delete all refresh tokens for that user.